package pt.mleiria.network.lowlevel;

import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import pt.mleiria.network.Command;
import pt.mleiria.network.utils.ServerConstants;

public class ServerBot {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		new ServerBot().startServer();
		
		
	}
	private void echo(final Socket connectionSocket, final byte cmdId) throws Exception{
		final OutputStream os = connectionSocket.getOutputStream();
		os.write(cmdId);
	}
	private void closeResources(final ServerSocket botSocket, final Socket connectionSocket, final InputStream is) throws IOException{
		is.close();
		connectionSocket.close();
		botSocket.close();
	}
	private void startServer(){
		ServerSocket botSocket = null;
		Socket connectionSocket = null;
		InputStream is = null;
		try{
			botSocket = new ServerSocket(ServerConstants.PORT);
			//for(;;){
			System.out.println("Accepting conn from commandBot");
			connectionSocket = botSocket.accept();
			while(true){
				is = connectionSocket.getInputStream();
				final byte cmdId = (byte)is.read();
				if(cmdId == -1){
					//closeResources(botSocket, connectionSocket, is); 
					break;
				}
				for(int i = 0; i < ServerConstants.commands.length; i++){
					if((ServerConstants.commands[i] ^ cmdId) == (byte)0x00){
						System.out.println(Command.parse(cmdId));
						echo(connectionSocket, cmdId);
					}
				}
			}//}
		}catch(EOFException e){
			try {
				System.out.println("End of command");
				closeResources(botSocket, connectionSocket, is);
			} catch (IOException e1) {
				System.out.println("Error closing DataInputStream...");
				e1.printStackTrace();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
